#include <iostream>
#include <pthread.h>
#include <unistd.h>
 
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
bool ready = false;
 
void* producer(void* arg) {
    sleep(1); // 模拟生产耗时
    pthread_mutex_lock(&mutex);
    ready = true; // 设置条件为真
    std::cout << "Producer: Resource is ready!\n";
    pthread_cond_signal(&cond); // 唤醒消费者
    pthread_mutex_unlock(&mutex);
    return nullptr;
}
 
void* consumer(void* arg) {
    pthread_mutex_lock(&mutex);
    while (!ready) { // 检查条件
        std::cout << "Consumer: Waiting for resource...\n";
        pthread_cond_wait(&cond, &mutex); // 等待条件变量
    }
    std::cout << "Consumer: Resource is consumed!\n";
    pthread_mutex_unlock(&mutex);
    return nullptr;
}
 
int main() {
    pthread_t producer_thread, consumer_thread;
    pthread_create(&producer_thread, nullptr, producer, nullptr);
    pthread_create(&consumer_thread, nullptr, consumer, nullptr);
 
    pthread_join(producer_thread, nullptr);
    pthread_join(consumer_thread, nullptr);
 
    return 0;
}
 